<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-row class="rolelist">
        <el-table
          :data="rolelist"
          border
          stripe
        >
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row
                :class="['bdbottom', index1 == 0 ? 'bdtop' : '','v-center']"
                :span="5"
                v-for="(item1, index1) in scope.row.children"
                :key="item1.id"
              >
                <!-- 渲染一级 -->
                <el-col :span="5">
                  <el-tag
                    closable
                    @close="removeRightById(scope.row, item1.id)"
                  >{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二级 -->
                <el-col :span="19">
                  <!-- 通过for循环嵌套渲染二级权限 -->
                  <el-row
                    v-for="(item2, index2) in item1.children"
                    :key="item2.id"
                    :class="[index2 !== 0 ? 'bdtop': '', 'v-center']"
                  >
                    <el-col :span="6">
                      <el-tag
                        @close="removeRightById(scope.row, item2.id)"
                        closable
                        type="success"
                      >{{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag
                        @close="removeRightById(scope.row, item3.id)"
                        closable
                        type="warning"
                        v-for="item3 in item2.children"
                        :key="item3.id"
                      >{{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column
            type="index"
            label="#"
          ></el-table-column>
          <el-table-column
            label="角色名称"
            prop="roleName"
          ></el-table-column>
          <el-table-column
            label="角色描述"
            prop="roleDesc"
          ></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <!-- 修改 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
              >编辑</el-button>
              <!-- 删除按钮 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
              >删除</el-button>
              <!-- 分配权限按钮 -->
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRightDiglog(scope.row)"
              >分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-card>
    <!-- 分配权限框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDiglogVisible"
      width="50%"
    >
      <!-- 树型控件 -->
      <el-tree
        :props="treeProps"
        :data="rightslist"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      >
      </el-tree>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="setRightDiglogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="allotRights"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //所有角色列表
      rolelist: [],
      //分配权限对话框
      setRightDiglogVisible: false,
      //所有权限的数据
      rightslist: [],
      //树型控件
      treeProps: {
        label: "authName",
        children: "children",
      },
      //默认选中的节点id值数组
      defKeys: [],
      //当前即将分配权限的角色id
      roleId: ''
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //获取所有角色
    async getRolesList() {
      const data = await this.$http.get("/roles");
      // console.log(data);
      if (data.status != 200) return this.$message.error("获取角色列表失败");
      this.rolelist = data.data.data;
      // console.log(data.data.data);
    },
    //删除标签权限
    removeRightById(role, id) {
      this.$confirm("此操作将删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // console.log(role);
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${id}`
          );
          // console.log(res);
          if (res.meta.status !== 200)
            return this.$message.error("删除用户权限失败");
          // this.getRolesList();
          role.children = res.data;
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //展示分配权限的对话框
    async showSetRightDiglog(role) {
      this.roleId = role.id;
      //获取所有数据
      const data = await this.$http.get("rights/tree");
      // console.log(data);
      if (data.status !== 200)
        return this.$message.error("获取用户权限列表失败");
      this.rightslist = data.data.data;

      //获取所有节点id
      this.getLeafKeys(role, (this.defKeys = []));

      this.setRightDiglogVisible = true;
    },
    //递归获取数组id
    getLeafKeys(node, arr) {
      if (!node.children) return arr.push(node.id);
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    //分配权限的函数
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      this.setRightDiglogVisible = false;
      // console.log(keys);
      const idStr = keys.join(',');
      const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`, {rids: idStr});
       if (res.meta.status !== 200) return this.$message.error("修改用户列表失败");
       this.$message.success("修改用户列表成功");
       this.getRolesList();//刷新列表
    },
  },
};
</script>

<style lang="stylus" scoped>
.el-card {
  margin-top: 15px;

  .rolelist {
    margin-top: 15px;

    .el-tag {
      margin: 7px;
    }
  }

  .bdtop {
    border-top: 1px solid #eee;
  }

  .bdbottom {
    border-bottom: 1px solid #eee;
  }

  .v-center {
    display: flex;
    align-items: center;
  }
}
</style>